using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using elibrary.Classes;
using elibrary.Models;
using elibrary.Models.Entities;

namespace elibrary.Models.Managers
{
	public class CategoryManager
	{
		private DataContext ctx;
		private DbSet<Category> categories;

		public CategoryManager(DataContext ctx)
		{
			this.ctx = ctx;
			this.categories = ctx.categories;
		}

		public void add(Category category,bool autoSave=true)
		{
			categories.Add(category);
			
			if (autoSave)
				ctx.SaveChanges();
		}

		public Category get(int id)
		{
			return categories.SingleOrDefault(q => q.id == id);
		}

		public Category get(string name)
		{
			var r = categories.Where(q => q.name.ToLower() == name.ToLower());

			return r != null && r.Any() ? r.First() : null;
		}

		public void delete(Category cat,bool autoSave=true)
		{
			if (cat == null)
				return;

			categories.Remove(cat);
			if (autoSave)
				ctx.SaveChanges();
		}

		public void delete(int uid,bool autoSave=true)
		{
			delete(get(uid),autoSave);
		}

		public void delete(string name,bool autoSave=true)
		{
			delete(get(name),autoSave);
		}
	}
}